﻿
     function GetTodayString() {
         var today = new Date();
         var month = today.getMonth() + 1;
         var day = today.getDate();
         var strMonth;
         var strDay;
         if (month < 10) {
             strMonth = "0" + month;
         }
         else {
             strMonth = month;
         }
         if (day < 10) {
             strDay = "0" + day;
         }
         else {
             strDay = day; 
         }
         var strtoday = today.getFullYear() + "-" + strMonth + "-" + strDay;
         return strtoday;

     }


     $(function () {
         $("#Fromdatepicker").datepicker();
         $("#Fromdatepicker").datepicker("option", "dateFormat", "yy-mm-dd");
         $("#Fromdatepicker").val(GetTodayString());

         $("#Todatepicker").datepicker();
         $("#Todatepicker").datepicker("option", "dateFormat", "yy-mm-dd");
         $("#Todatepicker").val(GetTodayString());
     });

      $.widget("ui.timespinner", $.ui.spinner, {
          options: {
              // seconds
              step: 60 * 1000,
              // hours
              page: 60
          },

          _parse: function (value) {
              if (typeof value === "string") {
                  // already a timestamp
                  if (Number(value) == value) {
                      return Number(value);
                  }
                  return +Globalize.parseDate(value);
              }
              return value;
          },

          _format: function (value) {
              return Globalize.format(new Date(value), "t");
          }
      });

      $(function () {
          Globalize.culture("de-DE");
          $("#spinnerTimeFrom").timespinner();
          $("#spinnerTimeTo").timespinner();
      });

     $(function () {
         showCont();
         $(":radio[name=pagemode]").click(function () {
             showCont();
         });
     });
      function showCont() {
          switch ($(":radio[name=pagemode]:checked").attr("id")) {
              case "pagemode_refresh":
                  $("#Todatepicker").hide();
                  $("#labelTodatepicker").hide();
                  $("#lableFunctionalTest").hide();
                  $("#selectfunctionalTest").hide();
                  break;
              case "pagemode_fixed":
                  if (ginterval != null) {
                      clearInterval(ginterval);
                  }
                  $("#Todatepicker").show();
                  $("#labelTodatepicker").show();
                  $("#lableFunctionalTest").show();
                  $("#selectfunctionalTest").show();
                  break;
              default:
                  break;
          }
      }

    $(function () {
        loadLineList();

        $("#selectline").change(function () {
            loadPartNoList();
        });

        $("#selectPartNo").change(function () {
            loadTestPlanItemList();
        });

        $("#selectTestPlan").change(function () {
            loadFunctionalTestList();
        });
    });

    function appendSelectOptions(queryResult, element) {
        element.empty();
        var result = jQuery.parseJSON(queryResult);
        for (var i = 0; i < result.length; i++) {
            element.append("<option value='" + result[i] + "'>" + result[i] + "</option>");   
        }
    }

    function loadLineList() {
        $.ajax({
            type: "post",
            url: "Default.aspx/GetLineList",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            data: null,
            success: function (res) {
                appendSelectOptions(res.d, $("#selectline"));
                loadPartNoList();
            },
            error: function (xmlReq, err, c) { alert("error" + err + c) }
        });
     
    }

    function loadPartNoList() {
        var selectLineId = $("#selectline").val();
        $.ajax({
            type: "post",
            url: "Default.aspx/GetPartNoListByLineID",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            data: "{'lineID':'" + selectLineId + "'}",
            success: function (res) {
                appendSelectOptions(res.d, $("#selectPartNo"));
                loadTestPlanItemList();
            },
            error: function (xmlReq, err, c) { alert("error" + err + c) }
        });
    }

    function loadFunctionalTestList() {
        var selectTestSeriesID = $("#selectTestPlan").val();
        $.ajax({
            type: "post",
            url: "Default.aspx/GetFunctionalTestIDList",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            data: "{'testSeriesID':'" + selectTestSeriesID + "'}",
            success: function (res) {
                $("#selectfunctionalTest").empty();
                var result = jQuery.parseJSON(res.d);
                for (var i = 0; i < result.length; i++) {
                    $("#selectfunctionalTest").append("<option value='" + result[i].Value + "'>" + result[i].Description + "</option>");
                }
            },
            error: function (xmlReq, err, c) { alert("error" + err + c) }
        });
    }

    function loadTestPlanItemList() {
        var selectLineId = $("#selectline").val();
        var selectPartNoId = $("#selectPartNo").val();
        $.ajax({
            type: "post",
            url: "Default.aspx/GetTestPlanItemListByLineIDPartNoID",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            data: "{'lineID':'" + selectLineId + "' , 'partNoID':'" + selectPartNoId + "'}",
            success: function (res) {
                $("#selectTestPlan").empty();
                var result = jQuery.parseJSON(res.d);
                for (var i = 0; i < result.length; i++) {
                    $("#selectTestPlan").append("<option value='" + result[i].Value + "'>" + result[i].Description + "</option>");
                }
                loadFunctionalTestList();
            },
            error: function (xmlReq, err, c) { alert("error" + err + c) }
        });


    }

    var ginterval;
    var gline;
    var gpartNo;
    var gtestPlanID;
    var gfunctionTestID;
    var gmetal;
    var gdateFrom;
    var gtimeFrom;
    var gdateTo;
    var gtimeTo;
    var gpageMode;
    var guclMode;
    var guclrMode
    var gXbar;
    var gRbar;

    $(document).ready(function () {
        $("#btnRefresh").click(function () {
            var selectLineId = $("#selectline").val();
            var selectPartNoId = $("#selectPartNo").val();
            var selectTestPlanId = $("#selectTestPlan").val();
            var selectTestPlanDes = $("#selectTestPlan").find("option:selected").text();
            var selectFunctionalTestId = $("#selectfunctionalTest").val();
            var xBar = $("#xBar").val();
            var rBar = $("#rBar").val();
            var dateFrom = $("#Fromdatepicker").val();
            var dateTo = $("#Todatepicker").val();
            var timeFrom = $("#spinnerTimeFrom").val();
            var timeTo = $("#spinnerTimeTo").val();
            var pageMode = $(":radio[name=pagemode]:checked").val();
            var uclMode = $(":radio[name=ulcmode]:checked").val();
            var uclrMode = $(":radio[name=ulcrmode]:checked").val();

            var message = "";
            if (xBar != "" && !IsNumber(xBar)) {
                message = message + "Please input a correct value to Xbar \n";
            }
            if (rBar != "" && !IsNumber(rBar)) {
                message = message + "Please input a correct value to Rbar \n";
            }
            if (!IsDate(dateFrom)) {
                message = message + "Please input a correct value to Date From \n";
            }
            if (pageMode > 0 && !IsDate(dateTo)) {
                message = message + "Please input a correct value to Date To \n";
            }
            if (!IsTime(timeFrom)) {
                message = message + "Please input a correct value to Time From \n";
            }
            if (!IsTime(timeTo)) {
                message = message + "Please input a correct value to Time To \n";
            }

            if (message != "") {
                alert(message);
                return;
            }

            //alert(selectLineId + selectPartNoId + selectTestPlanId + selectTestPlanDes + xBar + rBar + dateFrom + dateTo + timeFrom + timeTo + pageMode + uclMode);

            if (ginterval != null) {
                clearInterval(ginterval);
            }

            showChartM(selectLineId, selectPartNoId, selectTestPlanId, selectTestPlanDes, selectFunctionalTestId, dateFrom, dateTo, timeFrom, timeTo, pageMode, uclMode, uclrMode, xBar, rBar);

        });

    });

    function showChartM(lineID, partNoID, testPlanID, testPlanDes, functionalTestId, dateFrom, dateTo, timeFrom, timeTo, pageMode, uclMode, uclrMode, xBar, rBar) {
        $.ajax({
            type: "post",
            url: "Default.aspx/GetChartData",
            contentType: "application/json;charset=utf-8",
            dataType: "json",
            async: true,
            data: "{'lineID':'" + lineID + "','partNoID':'" + partNoID + "','testPlanID':'" + testPlanID + "','functionalTestID':'" + functionalTestId + "','dateFrom':'" + dateFrom +
            "','dateTo':'" + dateTo + "','timeFrom':'" + timeFrom + "','timeTo':'" + timeTo + "','xBar':'" + xBar + "','rBar':'" + rBar + "','isUCLFixed':'" + uclMode + "','isUCLRFixed':'" + uclrMode + "','isNextSeries':'" + 0 + "','isFixed':'" + pageMode + "'}",
            success: function (res) {
                var chartData = jQuery.parseJSON(res.d);
                if(chartData.LineHasNoValue == true)
                {
                    alert("No test data in this Line, please choose another line");
                }
                else
                {
                    setGlobleData(lineID, partNoID, testPlanID, testPlanDes, dateFrom, dateTo, timeFrom, timeTo, pageMode, uclMode, uclrMode, xBar, rBar);

                    LoadLine(chartData);
                
                    if($(":radio[name=pagemode]:checked").val() == 0) {
                        ginterval = setInterval("showChart()", 30000);
                    }
                }
            },
            error: function (xmlReq, err, c) { alert("error" + err + c) }
        });


    }

    function setGlobleData(lineID, partNoID, testPlanID, testPlanItem, dateFrom, dateTo, timeFrom, timeTo, pageMode, uclMode, uclrMode, xBar, rBar) {
        gline = lineID;
        gdateFrom = dateFrom;
        gtimeFrom = timeFrom;
        gdateTo = dateTo;
        gtimeTo = timeTo;
        gpageMode = pageMode;
        guclMode = uclMode;
        guclrMode = uclrMode;
        gXbar = xBar;
        gRbar = rBar; 
    }

    function showChart() {
            $.ajax({
                type: "post",
                url: "Default.aspx/GetChartData",
                contentType: "application/json;charset=utf-8",
                dataType: "json",
                async: true,
                data: "{'lineID':'" + gline + "','partNoID':'" + gpartNo + "','testPlanID':'" + gtestPlanID + "','functionalTestID':'" + gfunctionTestID + "','dateFrom':'" + gdateFrom +
            "','dateTo':'" + gdateTo + "','timeFrom':'" + gtimeFrom + "','timeTo':'" + gtimeTo + "','xBar':'" + gXbar + "','rBar':'" + gRbar + "','isUCLFixed':'" + guclMode + "','isUCLRFixed':'" + guclrMode + "','isNextSeries':'" + 1 + "','isFixed':'" + gpageMode + "'}",
                success: function (res) {
                    var chartData = jQuery.parseJSON(res.d);
                    LoadLine(chartData);
                },
                error: function (xmlReq, err, c) { alert("error" + err + c) }
            });
    }

    function LoadLine(chartData) {
        
        gfunctionTestID = chartData.OutputData.FunctionalTestID;
        gpartNo = chartData.OutputData.PartNoID;
        gtestPlanID = chartData.OutputData.TestPlanID;

        if (chartData.OutputData.IsRemark == true) {
            $("#isRemark").text("Remark");
        }
        else
        { $("#isRemark").text(""); }

        $("#pchartInfo").empty();
        $("#pchartInfo").append("Line: <b class=\"blue\"> " + gline + "</b> &nbsp");
        $("#pchartInfo").append("PartNo: <b class=\"blue\"> " + gpartNo + "</b> &nbsp");
        $("#pchartInfo").append("Test Plan Item: <b class=\"blue\"> " + chartData.OutputData.TestPlanDes + "</b> &nbsp");
        $("#pchartInfo").append("Functional Test ID: <b class=\"blue\"> " + chartData.OutputData.FunctionalTestDes + "</b> &nbsp");
        //var strChartInfo = "Line: " + gline + " | PartNo: " + gpartNo + " | Test Plan Item: " + gtestPlanItem + " | Functional Test ID: " + chartData.OutputData.FunctionalTestDes;
        //bind ChartInfo;
        if (chartData.HasChart == true) {
            $("#pchartInfo").append("CP: <b class=\"blue\"> " + chartData.OutputData.CP + "</b> &nbsp");
            $("#pchartInfo").append("CPK: <b class=\"blue\">" + chartData.OutputData.CPK + "</b> &nbsp");
//            strChartInfo = strChartInfo + " | CP: " + chartData.OutputData.CP  + " | CPK: " + chartData.OutputData.CPK;
        }


        if (chartData.HasChart == false) {
            $('#individualsContainer').empty();
            $('#movingRangeContainer').empty();
            return;
        }

        if (chartData.OutputData.ChartWidth > 920) {
            $('#individualsContainer').width(chartData.OutputData.ChartWidth);
            $('#movingRangeContainer').width(chartData.OutputData.ChartWidth);
        }
        else {
            $('#individualsContainer').width(920);
            $('#movingRangeContainer').width(920);
        }
        

        var individualChart = chartData.IndividualChart;
        var movingRangeChart = chartData.MovingRangeChart;
        var individualChartLength = individualChart.Categories.length - 1;
        var movingRangeLength = movingRangeChart.Categories.length - 1;
        Highcharts.setOptions({
            colors: ['#00FF00', '#FF0000', '#FF0000', '#00BFFF', '#00BFFF', '#000000', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
        });
        $('#individualsContainer').highcharts({
            title: {
                text: 'Individuals',
                x: -20 //center
            },
            legend: {
                verticalAlign: 'top',
                x: 240,
                floating: true,
                itemDistance: 10,
            },
            xAxis: {
                categories: individualChart.Categories
            },

            series: [
           
            {
                name: "X-Bar",
                data: [{ y: individualChart.AverageValue, x: 0 }, { y: individualChart.AverageValue, x: individualChartLength}]
            },
            {
                name: "UCL",
                data: [{ y: individualChart.UCLValue, x: 0 }, { y: individualChart.UCLValue, x: individualChartLength}]
            },
            {
                name: "LCL",
                data: [{ y: individualChart.LCLValue, x: 0}, { y: individualChart.LCLValue, x: individualChartLength}]
            },
            {
                name:"USL",
                data: [{ y: individualChart.USLValue, x: 0 }, { y: individualChart.USLValue, x: individualChartLength}]
            },
            {
                name: "LSL",
                data: [{ y: individualChart.LSLValue, x: 0 }, { y: individualChart.LSLValue, x: individualChartLength}]
            },
            {
                name: 'Individual',
                data: individualChart.LineData //[71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4],
            },

            ]
        });
        Highcharts.setOptions({
            colors: ['#00FF00', '#FF0000', '#000000', '#00BFFF', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
        });
        $('#movingRangeContainer').highcharts({
            title: {
                text: 'Moving Range',
                x: -20 //center
            },
            legend: {
                verticalAlign: 'top',
                x: 240,
                floating: true,
                itemDistance: 10,
            },
            xAxis: {
                categories: movingRangeChart.Categories
            },

            series: [
            {
                name: "R-Bar",
                data: [{ y: movingRangeChart.AverageValue, x: 1 }, { y: movingRangeChart.AverageValue, x: movingRangeLength}]
            },

            {
                name: "UCLR",
                data: [{ y: movingRangeChart.UCLValue, x: 1 }, { y: movingRangeChart.UCLValue, x: movingRangeLength}]
            },
            {
                name: 'moving Range',
                data: movingRangeChart.LineData
            },
            ]
        });
    }
    	   
    function IsNumber(input) {
        var regex = /^-?\d+$|^(-?\d+)(\.\d+)?$/;
        if (input.match(regex)) {
            return true;
        } else {
            return false;
        }
    }

    function IsDate(input) {
        var regex = /^((?:19|20)\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;
        if (input.match(regex)) {
            return true;
        }
        else {
            return false;
        }
    }

    function IsTime(input) {
        var regex = /^(([0-1][0-9])|(2[0-4])):[0-5][0-9]$/;
        if (input.match(regex)) {
            return true;
        }
        else {
            return false; 
        }
    }
